import React, { useContext, useState, useEffect, useRef } from 'react';
import {
  message,
  Drawer,
  Form,
  Input,
  Button,
  Radio,
  InputNumber,
  Table,
  Spin,
  Popconfirm,
  Modal,
} from 'antd';
import {
  upadataField,
  getMappingByTableid,
  createStructurebybaseTable,
  savaFile,
  createTargetTable,
  removeField,
  setTargetTable,
} from '../api';

const EditableContext = React.createContext(null);

const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={[
          {
            required: false,
            message: `${title} is required.`,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          width: '100%',
          minHeight: 20,
          paddingRight: 24,
        }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

const DataFrame = props => {
  // 结构化数据
  const { visible, onCancel, onSuccess, data, type, currentIndex = 0 } = props;

  // 初始化 form
  const [form] = Form.useForm();
  const [count, setCount] = useState(0);
  const [loading, setLoading] = useState(false);
  const [listData, setListData] = useState([]); // 映射字段
  const [sqlData, setSqlData] = useState([]); //sql 语句

  const [itemId, setItemId] = useState();
  const [isModalVisible, setIsModalVisible] = useState(false);

  const [tableName, setTableName] = useState('');

  const showModal = () => {
    setIsModalVisible(true);
  };

  const setName = e => {
    setTableName(e.target.value);
  };
  // 设置表名
  const handleOk = () => {
    setLoading(true);
    const paylaod = {
      id: data.id,
      name: tableName,
    };
    setTargetTable(paylaod).then(res => {
      setLoading(false);
      if (res.code === 0) {
        message.success('操作成功！');
        setIsModalVisible(false);
      } else {
        message.error(res.msg || '操作失败，请重试');
      }
    });
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  // 详情
  const getDetailData = () => {
    const paylaod = {
      id: data.id,
    };
    setLoading(true);
    getMappingByTableid(paylaod).then(res => {
      console.log(23323);
      setLoading(false);
      if (res.code === 0) {
        setItemId(res.data.id);
        const structure = res.data.structures || [];
        setListData(structure);
      } else {
        message.error(res.msg || '获取详情失败');
      }
    });
  };

  useEffect(() => {
    visible === true && getDetailData();
  }, [visible]);

  // 栅格化
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  };

  /**
   * @en-US Update node
   * @zh-CN values
   *
   * @param fields
   */
  const updataData = values => {
    const hide = message.loading('正在添加');
    setLoading(true);

    const requirement = values.requirement ? ` where ${values.requirement}` : '';

    const paylaod = {
      comms: `select ${values.fields} from ${sqlData.tableName}${requirement}`,
      current: 1,
      pageSize: 10,
      firstcolumn: sqlData.firstcolumn,
      dataSourceId: sqlData.dataSourceId,
      pri: sqlData.pri,
      type: '1',
      dataUnitId: sqlData.dataUnitId,
    };
    upadataField(paylaod).then(res => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || '修改失败，请重试');
      }
    });
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param values
   */
  const sendData = () => {
    form.validateFields().then(values => {
      updataData(values);
    });
  };

  const modelClose = () => {
    onCancel(false);
  };

  //生成缺省字段
  const clickCreateStructurebybaseTable = () => {
    setLoading(true);
    createStructurebybaseTable({ id: itemId }).then(res => {
      setLoading(false);
      if (res.code === 0) {
        getDetailData();
      }
    });
  };

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };

  const handleSave = row => {
    console.log('row', row);
    const newData = JSON.parse(JSON.stringify(listData));
    const index = newData.findIndex(
      item => (row.key && row.key === item.key) || (row.id && row.id === item.id),
    );
    const item = newData[index];

    console.log('item', item);
    newData.splice(index, 1, { ...item, ...row });
    setListData(newData);
  };

  const handleAdd = () => {
    const newData = {
      key: count,
      columnName: '',
      columnType: '',
      columnValue: '',
      columnComment: '',
    };
    setListData([...listData, newData]);
    setCount(count + 1);
  };

  const handleDelete = index => {
    const dataSource = JSON.parse(JSON.stringify(listData));

    for (var i = 0; i < dataSource.length; i++) {
      if (index === i) {
        dataSource.splice(index, 1);
        break;
      }
    }
    // dataSource.forEach((item) => {
    //   dataSource.splice(index, 1)
    // })
    setListData(dataSource);

    // this.setState({
    //   dataSource: dataSource.filter((item) => item.key !== key)
    // })
  };

  //保存
  const save = () => {
    const payload = {
      id: data.id,
      structures: listData,
    };
    setLoading(true);
    savaFile(payload).then(res => {
      setLoading(false);
      if (res.code === 0) {
        message.success('保存成功！');
      } else {
        message.error(res.msg || '保存失败，请重试');
      }
    });
  };

  // 生成目标表
  const clickCreateTargetTable = () => {
    const payload = {
      id: data.id,
    };
    setLoading(true);
    createTargetTable(payload).then(res => {
      setLoading(false);
      if (res.code === 0) {
        message.success('生成成功！');
      } else {
        message.error(res.msg || '生成失败，请重试');
      }
    });
  };

  const delTargetTable = () => {
    // const payload = {
    //   id: data.id,
    // };
    setLoading(true);
    removeField(data.id).then(res => {
      setLoading(false);
      if (res.code === 0) {
        message.success('删除成功！');
      } else {
        message.error(res.msg || '删除失败，请重试');
      }
    });
  };

  const column = [
    {
      title: '序号',
      dataIndex: 'columnPosition',
      key: 'columnPosition',
      width: 100,
      editable: true,
    },
    {
      title: '列名',
      dataIndex: 'columnName',
      key: 'columnName',
      width: 100,
      editable: true,
    },
    {
      title: '类型',
      dataIndex: 'columnType',
      key: 'columnType',
      width: 100,
      editable: true,
    },
    {
      title: '映射值',
      dataIndex: 'columnValue',
      key: 'columnValue',
      width: 100,
      editable: true,
    },
    {
      title: '备注',
      dataIndex: 'columnComment',
      key: 'columnComment',
      width: 100,
      editable: true,
    },
    {
      title: '加密',
      dataIndex: 'security',
      key: 'security',
      width: 100,
      editable: true,
    },
    {
      title: '操作',
      dataIndex: 'opt',
      key: 'columnCooptmment',
      width: 100,
      render: (value, row, index) => {
        return (
          <Popconfirm
            placement="topRight"
            title="确认要删除此行吗？"
            onConfirm={() => handleDelete(index)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link">删除</Button>
          </Popconfirm>
        );
      },
    },
  ];

  const columns = column.map(col => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: record => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave: handleSave,
      }),
    };
  });
  return (
    <Spin spinning={loading}>
      <div style={{ marginBottom: 10 }}>表名称：{data.tableName}</div>
      <Table
        rowKey={record => record.id}
        components={components}
        columns={columns}
        dataSource={listData}
        bordered
        size="middle"
        pagination={false}
      />
      <div style={{ marginTop: 20 }}>
        对称加密：SM4,DES,3DES,AES,PBE; 非对称加密：SM2,RSA,ElGamal
      </div>
      <div style={{ marginTop: 20 }}>
        <Button type="primary" danger onClick={handleAdd} style={{ marginRight: 20 }}>
          添加行
        </Button>
        <Popconfirm
          placement="topRight"
          title="自动生成，将删除已有映射配置，确认要自动生成吗？"
          onConfirm={clickCreateStructurebybaseTable}
          okText="确定"
          cancelText="取消"
        >
          <Button type="primary">生成缺省字段</Button>
        </Popconfirm>
        <Button type="primary" danger onClick={save} style={{ marginLeft: 20 }}>
          保存
        </Button>
        <Popconfirm
          placement="topRight"
          title="确认要生成目标表吗？"
          onConfirm={clickCreateTargetTable}
          okText="确定"
          cancelText="取消"
        >
          <Button type="primary" style={{ marginLeft: 40 }}>
            生成目标表
          </Button>
        </Popconfirm>
        <Popconfirm
          placement="topRight"
          title="确认要删除目标表吗？"
          onConfirm={delTargetTable}
          okText="确定"
          cancelText="取消"
        >
          <Button type="primary" danger style={{ marginLeft: 20 }}>
            删除目标表
          </Button>
        </Popconfirm>
        <Popconfirm
          placement="topRight"
          title="确认要指定目标表吗？"
          onConfirm={showModal}
          okText="确定"
          cancelText="取消"
        >
          <Button type="primary" style={{ marginLeft: 20 }}>
            指定目标表
          </Button>
        </Popconfirm>
      </div>

      <Modal title="指定目标表" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <Input type="text" size="50" placeholder="请输入指定目标表名称" onChange={{ setName }} />
      </Modal>
    </Spin>
  );
};

export default DataFrame;
